package com.binguo.api.baidu;

import com.binguo.api.baidu.model.Dishes;
import com.binguo.api.baidu.model.ImgTag;
import com.binguo.api.baidu.model.Location;
import com.binguo.api.baidu.model.Result;
import com.binguo.api.businessmodel.ProductImgDetailModel;
import com.binguo.api.businessmodel.ProductImgModel;
import com.binguo.api.huawei.imagesearch.model.HuaweiProduct;
import com.binguo.api.huawei.imagesearch.model.RecResult;
import com.binguo.api.imgrec.ImgRecResult;
import com.binguo.api.imgrec.Results;
import com.binguo.api.response.product.ProductRecResultDetailVONewWithLocation;
import com.binguo.api.response.product.ProductRecResultVONewWithLocation;
import com.binguo.api.schedule.DataLoadService;
import com.binguo.common.paymodel.ThreadManager;
import com.binguo.common.util.JsonUtil;
import com.binguo.model.mapper.LogProductRecMapper;
import com.binguo.model.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;


@Service
public class BaiduRecUtilShiZhengFu {

    private static Logger logger = LoggerFactory.getLogger(BaiduRecUtilShiZhengFu.class);

    @Autowired
    private BaiduRecUtil baiduRecUtil;



    @Resource
    private LogProductRecMapper logProductRecMapper;

    /**
     * 餐盘格子识别
     * @param shopId
     * @param fileBase64Content
     * @param filename
     * @param outputFilepath
     * @param uuidFileName
     * @param imgUrl
     * @param sourceImgOnInternet
     * @param branchId
     * @param recType
     * @param imgWidth
     * @return
     * @throws Exception
     */
    public ProductRecResultVONewWithLocation searchWithPalletCell(Integer shopId, String fileBase64Content,
                                                                  String filename, String outputFilepath,
                                                                  String uuidFileName,
                                                                  String imgUrl, String sourceImgOnInternet, Integer branchId, Integer recType,
                                                                  Integer imgWidth
    ) throws Exception {

        Date date = Calendar.getInstance().getTime();
        long startTime = date.getTime();
        logger.info("开始识别:" + startTime);
        long localrecStart = System.currentTimeMillis();

        List<ProductYpRef> productYpRefList = null;
        if (DataLoadService.shopYpProductListMap != null) {
            productYpRefList = DataLoadService.shopYpProductListMap.get(shopId);
        }

        String token;

        int width = 30;
        if (imgWidth != null && imgWidth > 1000) {
            width = 80;
//            width = 60;
        }

        if (recType != null && recType.equals(1)) {
            token = baiduRecUtil.getBaiduToken(shopId, branchId);

        }else {
            if(DataLoadService.shopBaiduUrlCurListMap.get(shopId) != null){
                Map<String, String> tokenMap = baiduRecUtil.getBaiduTokenCurTempList(shopId, branchId);
                token = tokenMap.get("token");
                if (token == null) {
                    token = baiduRecUtil.getBaiduToken(shopId, branchId);
                }
            }else {
                token = baiduRecUtil.getBaiduToken(shopId, branchId);
            }
        }

        String tempToken = token;


        Future<RecResult> bowlRecResultFuture = getBowlResult(shopId, sourceImgOnInternet);

        Future<RecResult> huaRecResultFuture = getProductYp(productYpRefList, shopId, sourceImgOnInternet);


        RecResult huaRecResult = bowlRecResultFuture.get();



        long errorExistStart = System.currentTimeMillis();


        ProductImgModel productImgModel = new ProductImgModel();
        productImgModel.setProductOrderNo(uuidFileName);
        productImgModel.setShopId(shopId);
        productImgModel.setSourceFilename(filename);
        productImgModel.setUuidFileName(uuidFileName);
        productImgModel.setImgUrl(imgUrl);
        productImgModel.setCurIpAddress(baiduRecUtil.ipAddress);
        productImgModel.setSourceImgOnInternet(sourceImgOnInternet);
        productImgModel.setItemList(new ArrayList<>());

        final List<ImgTag> imgTagList = new ArrayList<>();

        ProductRecResultVONewWithLocation productRecResultVO = new ProductRecResultVONewWithLocation();
        productRecResultVO.setProductList(new ArrayList<>());
        productRecResultVO.setTotalFee(0l);
        productRecResultVO.setRealFee(0l);
        if (huaRecResult != null) {
            int index = 0;
            int seq = 1;


            List<Result> searchResultList = new ArrayList<>();

            for (int i=0; i < huaRecResult.getDetectionClasses().size(); i++) {

                double score = huaRecResult.getDetectionScores().get(i);

                if (score > 0.5) {
//                if (score > DataLoadService.huaweiScore) {
                    List<Double> boxes = huaRecResult.getDetectionBoxes().get(i);

                    if (boxes.get(0) < 10 && boxes.get(1) < 10) {
                        continue;
                    }

                    int y1 = boxes.get(0).intValue();
                    int x1 = boxes.get(1).intValue();

                    int y2 = boxes.get(2).intValue();
                    int x2 = boxes.get(3).intValue();


                    Result temp = new Result();
                    temp.setLocation(new Location());
                    temp.getLocation().setLeft(x1);
                    temp.getLocation().setTop(y1);
                    if (x2 > x1) {
                        temp.getLocation().setWidth(x2 - x1);
                    } else {
                        temp.getLocation().setWidth(x1 - x2);
                    }
                    if (y2 > y1) {
                        temp.getLocation().setHeight(y2 - y1);
                    } else {
                        temp.getLocation().setHeight(y1 - y2);
                    }

                    temp.setDishes(new ArrayList<>());
                    Dishes dishes = new Dishes();
                    dishes.setBrief(huaRecResult.getDetectionClasses().get(i));
                    dishes.setScore(score);
                    temp.getDishes().add(dishes);

                    searchResultList.add(temp);
                }
            }

            List<Result> needRemovedList = null;

            for (Result temp : searchResultList) {
                int x1 = temp.getLocation().getLeft();
                int y1 = temp.getLocation().getTop();

                int x2 = temp.getLocation().getLeft() + temp.getLocation().getWidth();
                int y2 = temp.getLocation().getTop() + temp.getLocation().getHeight();

                //右上角坐标
                int y11 = y1;
                int x11 = x2;

                for (Result compare : searchResultList) {
                    int x3 = compare.getLocation().getLeft();
                    int y3 = compare.getLocation().getTop();

                    int x4 = compare.getLocation().getLeft() + compare.getLocation().getWidth();
                    int y4 = compare.getLocation().getTop() + compare.getLocation().getHeight();

                    //右上角坐标
                    int y22 = y3;
                    int x22 = x4;

                    if (x1 < x3 && y1 < y3
                            && x2 > x4 && y2 > y4
                            ) {
                        logger.info("检测有图片包含: top=" + temp.getLocation().getTop());
                        if (needRemovedList == null) {
                            needRemovedList = new ArrayList<>();
                        }
                        needRemovedList.add(temp);
                    }

                    if (      ((x1 < (x3 + width) && x1 > (x3 - width))
                            && (y1 < (y3 + width) && y1 > (y3 - width)))

                            ||

                            ((x2 < (x4 + width) && x2 > (x4 - width))
                                    && (y2 < (y4 + width) && y2 > (y4 - width)))

                            ||

                            ((x11 < (x22 + width) && x11 > (x22 - width))
                                    && (y11 < (y22 + width) && y11 > (y22 - width)))


                            ){
                        if (x1 == x3 && y1 == y3 && x2 == x4) {
                            continue;
                        }

                        logger.info("检测附近有图片包含: top=" + temp.getLocation().getTop());
                        if (needRemovedList == null) {
                            needRemovedList = new ArrayList<>();
                        }

                        if (temp.getDishes().get(0).getScore() > compare.getDishes().get(0).getScore()) {
                            needRemovedList.add(compare);
                        }
                    }
                }

                /*if (huaweiProductList != null && huaweiProductList.size() > 0) {
                    for (HuaweiProduct huaweiProduct : huaweiProductList) {
                        int y3 = huaweiProduct.getLocation().get(0).intValue();
                        int x3 = huaweiProduct.getLocation().get(1).intValue();

                        int y4 = huaweiProduct.getLocation().get(2).intValue();
                        int x4 = huaweiProduct.getLocation().get(3).intValue();

                        //右上角坐标
                        int y22 = y3;
                        int x22 = x4;

                        if (x1 < x3 && y1 < y3
                                && x2 > x4 && y2 > y4
                                ) {
                            logger.info("检测有图片包含: top=" + temp.getLocation().getTop());
                            if (needRemovedList == null) {
                                needRemovedList = new ArrayList<>();
                            }
                            needRemovedList.add(temp);
                            continue;
                        }

                        if (       ((x1 < (x3 + width) && x1 > (x3 - width))
                                && (y1 < (y3 + width) && y1 > (y3 - width)))

                                ||

                                ((x2 < (x4 + width) && x2 > (x4 - width))
                                        && (y2 < (y4 + width) && y2 > (y4 - width)))

                                ||

                                ((x11 < (x22 + width) && x11 > (x22 - width))
                                        && (y11 < (y22 + width) && y11 > (y22 - width)))

                                ) {


                            logger.info("检测到云澎菜品库商品,id:" + huaweiProduct.getProductId() +
                                    ",name=" + huaweiProduct.getProductName() + ",baiduTop:" + x3);


                            if (needRemovedList == null) {
                                needRemovedList = new ArrayList<>();
                            }
                            needRemovedList.add(temp);
                        }

                    }
                }*/
            }


            List<Future<RecResult>> recFutureList = new ArrayList<>();

            for (Result temp : searchResultList) {
                boolean remove = false;
                if (needRemovedList != null) {
                    for (Result badResult : needRemovedList) {
                        if (badResult.getLocation().getTop() == temp.getLocation().getTop()
                                && badResult.getLocation().getWidth() == temp.getLocation().getWidth()
                                && badResult.getLocation().getHeight() == temp.getLocation().getHeight()
                                && badResult.getLocation().getLeft() == temp.getLocation().getLeft()
                                ) {
                            remove = true;
                            break;
                        }
                    }
                }

                if (remove) {
                    continue;
                }


                if (true) {

                    //针对框出来不识别的情况
                    logger.info("======框出识别:{}, {}, {}, {}", temp.getLocation().getTop(),
                            temp.getLocation().getLeft(), temp.getLocation().getWidth(), temp.getLocation().getHeight());


                    Integer tempSeq = seq;
                    Integer tempIndex = index;

                    ProductRecResultVONewWithLocation tempProductRecResultVO = productRecResultVO;
                    Future<RecResult> localRecFuture = ThreadManager.executorService.submit((Callable) () ->
                    {
                        long reRecStart = System.currentTimeMillis();
                        baiduRecUtil.handleNotRecImg(filename, shopId, uuidFileName,
                                temp, tempProductRecResultVO, tempSeq,
                                productImgModel, imgTagList, branchId, tempIndex, tempToken, recType);
                        long reRecEnd = System.currentTimeMillis();
                        logger.info("======框出后识别时间:{}, tempIndex:{}", reRecEnd - reRecStart, tempIndex);
                        return null;
                    });

                    recFutureList.add(localRecFuture);
                }




                index++;

                seq++;
            }

            for (Future<RecResult> recResultFuture : recFutureList) {
                recResultFuture.get();
            }
            long errorExistEnd = System.currentTimeMillis();

            logger.info("======框出重新识别时间:{}", errorExistEnd - errorExistStart);

            RecResult objectRecResult = null;
            if (huaRecResultFuture != null) {
                objectRecResult = huaRecResultFuture.get();
            }

            List<HuaweiProduct> huaweiProductList = null;
            if (objectRecResult != null) {
                List<String> stringProductYpRefMap = DataLoadService.shopYpProductSearchCodeListMap.get(shopId);

                huaweiProductList = new ArrayList<>();
                for (int i=0; i < objectRecResult.getDetectionClasses().size(); i++) {
                    String detectName = objectRecResult.getDetectionClasses().get(i);

                    if (stringProductYpRefMap!= null && stringProductYpRefMap.contains(detectName)) {
                        double score = objectRecResult.getDetectionScores().get(i);
                        if (score > 0.9) {
                            List<Double> boxes = objectRecResult.getDetectionBoxes().get(i);

                            if (boxes.get(0) < 10 && boxes.get(1) < 10) {
                                continue;
                            }

                            int y1 = boxes.get(0).intValue();
                            int x1 = boxes.get(1).intValue();

                            int y2 = boxes.get(2).intValue();
                            int x2 = boxes.get(3).intValue();

                            //右上角坐标
                            int y11 = y1;
                            int x11 = x2;

                            boolean addFlag = true;

                            boolean needRemove = false;
                            HuaweiProduct needRemoveObj = null;
                            for (HuaweiProduct huaweiProduct : huaweiProductList) {
                                int y3 = huaweiProduct.getLocation().get(0).intValue();
                                int x3 = huaweiProduct.getLocation().get(1).intValue();

                                int y4 = huaweiProduct.getLocation().get(2).intValue();
                                int x4 = huaweiProduct.getLocation().get(3).intValue();

                                //右上角坐标
                                int y22 = y3;
                                int x22 = x4;

                                if (       ((x1 < (x3 + width) && x1 > (x3 - width))
                                        && (y1 < (y3 + width) && y1 > (y3 - width)))

                                        ||

                                        ((x2 < (x4 + width) && x2 > (x4 - width))
                                                && (y2 < (y4 + width) && y2 > (y4 - width)))

                                        ||

                                        ((x11 < (x22 + width) && x11 > (x22 - width))
                                                && (y11 < (y22 + width) && y11 > (y22 - width)))

                                        ) {

                                    if (score > huaweiProduct.getScore()) {
                                        addFlag = true;
                                        needRemove = true;
                                        needRemoveObj = huaweiProduct;
                                        break;
                                    }else {
                                        addFlag = false;
                                    }
                                }
                            }
                            if (needRemove) {
                                for (HuaweiProduct huaweiProduct : huaweiProductList) {
                                    if (huaweiProduct.getProductId() == needRemoveObj.getProductId()
                                            && huaweiProduct.getScore() == needRemoveObj.getScore()
                                            ) {
                                        huaweiProductList.remove(huaweiProduct);
                                        break;
                                    }
                                }
                            }

                            if (addFlag) {
                                ProductYpRef temp = DataLoadService.getProductYpRefBySearchCode(detectName, shopId, branchId);
                                if (temp == null) {
                                    continue;
                                }
                                HuaweiProduct huaweiProduct = new HuaweiProduct();
                                huaweiProduct.setProductId(temp.getProductId());
                                huaweiProduct.setProductName(temp.getProductName());
                                huaweiProduct.setLocation(boxes);
                                huaweiProduct.setScore(objectRecResult.getDetectionScores().get(i));
                                huaweiProductList.add(huaweiProduct);
                            }
                        }
                    }
                }

            }

            Set<Result> findDuplicatedProductList = getRemoveList(searchResultList, huaweiProductList, width, productRecResultVO.getProductList());

            if (findDuplicatedProductList != null && findDuplicatedProductList.size() > 0 &&
                    productRecResultVO.getProductList() != null && productRecResultVO.getProductList().size() > 0) {
                logger.info("findDuplicatedProductIdList==" + findDuplicatedProductList);

                List<ProductRecResultDetailVONewWithLocation> toBeRemovedList = null;
                for (ProductRecResultDetailVONewWithLocation productRecResultDetailVONewWithLocation
                        : productRecResultVO.getProductList()) {

                    if (productRecResultDetailVONewWithLocation.getConfident() == 1) {
                        continue;
                    }

                    for (Result result : findDuplicatedProductList) {

                        Integer tobeRemovedProductId = Integer.valueOf(result.getDishes().get(0).getBrief());
                        if (tobeRemovedProductId.equals(productRecResultDetailVONewWithLocation.getProductId())) {
                            int x1 = result.getLocation().getLeft();
                            int y1 = result.getLocation().getTop();

                            int x2 = result.getLocation().getLeft() + result.getLocation().getWidth();
                            int y2 = result.getLocation().getTop() + result.getLocation().getHeight();

                            if (x1 == productRecResultDetailVONewWithLocation.getX1()
                                    && x2 == productRecResultDetailVONewWithLocation.getX2()
                                    && y1 == productRecResultDetailVONewWithLocation.getY1()
                                    && y2 == productRecResultDetailVONewWithLocation.getY2()
                                    ) {
                                if (toBeRemovedList == null) {
                                    toBeRemovedList = new ArrayList<>();
                                }
                                toBeRemovedList.add(productRecResultDetailVONewWithLocation);
                                break;
                            }
                        }
                    }

                }

                logger.info("toBeRemovedList==" + toBeRemovedList);
                if (toBeRemovedList != null) {
                    if (imgTagList != null && imgTagList.size() > 0) {
                        List<ImgTag> imgTagToBeRemoveList = new ArrayList<>();
                        for (ImgTag imgTag : imgTagList) {
                            for (ProductRecResultDetailVONewWithLocation productRecResultDetailVONewWithLocation : toBeRemovedList) {

                                if (
                                        productRecResultDetailVONewWithLocation.getX1().intValue() == imgTag.getX1()&&
                                        productRecResultDetailVONewWithLocation.getX2().intValue() == imgTag.getX2()&&
                                        productRecResultDetailVONewWithLocation.getY1().intValue() == imgTag.getY1()&&
                                        productRecResultDetailVONewWithLocation.getY2().intValue() == imgTag.getY2()
                                        ) {
                                    imgTagToBeRemoveList.add(imgTag);
                                    logger.info("to be remove imgTag==" + imgTag);
                                }
                            }
                        }
                        if (imgTagToBeRemoveList.size() > 0) {
                            imgTagList.removeAll(imgTagToBeRemoveList);
                        }
                    }
                    productRecResultVO.getProductList().removeAll(toBeRemovedList);
                    if (productRecResultVO.getProductList() == null) {
                        productRecResultVO.setProductList(new ArrayList<>());
                    }
                }


            }

            if (huaweiProductList != null && huaweiProductList.size() > 0) {
                for (HuaweiProduct huaweiProduct : huaweiProductList) {
                    Product product = DataLoadService.productMap.get(huaweiProduct.getProductId());

                    String label = seq + "、" + product.getName();

                    int y1 = huaweiProduct.getLocation().get(0).intValue();
                    int x1 = huaweiProduct.getLocation().get(1).intValue();

                    int y2 = huaweiProduct.getLocation().get(2).intValue();
                    int x2 = huaweiProduct.getLocation().get(3).intValue();

                    ImgTag imgTag = new ImgTag();
                    imgTag.setX1(x1);
                    imgTag.setY1(y1);
                    imgTag.setX2(x2);
                    imgTag.setY2(y2);
                    imgTag.setLabel(label);
                    imgTag.setScore(1);
                    imgTagList.add(imgTag);



                    /**
                     * save ProductImgDetailModel
                     */
                    ProductImgDetailModel productImgDetailModel = new ProductImgDetailModel();
                    productImgDetailModel.setProductName(product.getName());
                    productImgDetailModel.setProductId(product.getId());
                    productImgDetailModel.setSeq(seq);
                    productImgDetailModel.setLeft(x1);
                    productImgDetailModel.setTop(y1);
                    if (x2 > x1) {
                        productImgDetailModel.setWidth(x2 - x1);
                    }else {
                        productImgDetailModel.setWidth(x1 - x2);
                    }

                    if (y2 > y1) {
                        productImgDetailModel.setHeight(y2 - y1);
                    }else {
                        productImgDetailModel.setHeight(y1 - y2);
                    }
                    productImgDetailModel.setScore(1);

                    productImgModel.getItemList().add(productImgDetailModel);
                    ///----end

                    ProductRecResultDetailVONewWithLocation productRecResultDetailVO
                            = new ProductRecResultDetailVONewWithLocation();

                    productRecResultDetailVO.setX1(x1);
                    productRecResultDetailVO.setX2(x2);
                    productRecResultDetailVO.setY1(y1);
                    productRecResultDetailVO.setY2(y2);
                    productRecResultDetailVO.setConfident(1);

                    productRecResultDetailVO.setProductName(product.getName());
                    productRecResultDetailVO.setProductId(product.getId());

                    productRecResultDetailVO.setProductPrice(product.getPrice());
                    productRecResultDetailVO.setItemCount(1);
                    productRecResultDetailVO.setSeq(seq);

                    productRecResultVO.getProductList().add(productRecResultDetailVO);
                    productRecResultVO.setTotalFee(productRecResultVO.getTotalFee().longValue()
                            + product.getPrice().longValue());

                    seq++;
                }
            }



        }



        try {
                List<Result> searchResultList = null;

                if ((searchResultList != null && searchResultList.size() > 0)
                        || huaRecResult != null
                        ) {


                    ThreadManager.executorService.submit(() -> {
                        try {
                            baiduRecUtil.setKey(productImgModel.getProductOrderNo(), productImgModel, 60 * 60 * 1000);
                            ProductImgJsonInfo productImgJsonInfo = new ProductImgJsonInfo();
                            productImgJsonInfo.setProductContent(JsonUtil.toJson(productImgModel));
                            productImgJsonInfo.setProductOrderNo(productImgModel.getProductOrderNo());

                            baiduRecUtil.productImgJsonInfoMapper.insert(productImgJsonInfo);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });

                    productRecResultVO.setRealFee(productRecResultVO.getTotalFee());
                    productRecResultVO.setProductCount(productRecResultVO.getProductList().size());

                }

                if (productRecResultVO == null) {
                    return null;
                }

                String imgJson = JsonUtil.toJson(imgTagList);

                logger.info("imgJson==" + imgJson);
                String temp = Base64.getEncoder().encodeToString(imgJson.getBytes());
                logger.info(temp);

                imgJson = URLEncoder.encode(temp);
                logger.info(imgJson);

                long endTime2 = System.currentTimeMillis();
                logger.info("endTime3=" + endTime2 + ", intelval=" + (endTime2 - startTime));

                String tempOutputFilepath = outputFilepath.replaceAll("/usr/local/nginx/html", "/data/html");
                String tempFilename = filename.replaceAll("/usr/local/nginx/html", "/data/html");

                String drwaImgParam = "outputFilepath=" + tempOutputFilepath + "&filename=" + tempFilename + "&image=" + imgJson;

                HttpEntity drawEntity = new HttpEntity<>(drwaImgParam, baiduRecUtil.DEFAULT_JSON_HEADER);

                ResponseEntity<String> drwaImgResult = baiduRecUtil.restTemplate.postForEntity("http://"+baiduRecUtil.recIp+":8082/hello2", drawEntity, String.class);

                logger.info(drwaImgResult.getBody());


                long endTime3 = System.currentTimeMillis();
                logger.info("endTime4=" + endTime3 + ", intelval=" + (endTime3 - endTime2));

                if ("ok".equals(drwaImgResult.getBody())) {

                    ThreadManager.executorService.submit(() -> {
                        LogProductRec logProductRec = new LogProductRec();
                        logProductRec.setFilepath(filename);
                        logProductRec.setOutputFilepath(outputFilepath);
                        logProductRec.setCreateTime(date);
                        logProductRec.setShopId(shopId);
                        logProductRec.setImgSrcNetUrl(sourceImgOnInternet);
                        logProductRec.setRecResult(null);
                        logProductRec.setImgResultNetUrl(imgUrl);
                        logProductRecMapper.insert(logProductRec);
                    });

                    ShopPackageDiscount shopPackageDiscount = baiduRecUtil.checkProductPackage(shopId, productRecResultVO);

                    if (shopPackageDiscount != null) {
                        productRecResultVO.setRealFee(shopPackageDiscount.getPrice());
                        productRecResultVO.setMealSetName(shopPackageDiscount.getName());
                        productRecResultVO.setMealSetId(shopPackageDiscount.getId());
                    }

                    return productRecResultVO;
                }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private Integer bowlCount = 1;
    private Future<RecResult> getBowlResult(Integer shopId, String sourceImgOnInternet){
        Future<RecResult> localRecFuture = ThreadManager.executorService.submit((Callable) () ->
        {
            long localrecStart = System.currentTimeMillis();

            Map<String, String> param = new HashMap<>();
            param.put("shopId", shopId + "");
            param.put("imgUrl", sourceImgOnInternet);
            String jsonParam = JsonUtil.toJson(param);

            HttpEntity entity = new HttpEntity<>(jsonParam, baiduRecUtil.DEFAULT_JSON_HEADER_UTF8);


            String url = DataLoadService.bowlRecUrl;
            if(bowlCount == 1){
                url = DataLoadService.bowlRecUrl;
            } else if (bowlCount == 2) {
                url = DataLoadService.bowlRecUrl2;
            } else if (bowlCount == 3) {
                url = DataLoadService.bowlRecUrl3;
            }
            bowlCount++;

            if (bowlCount > 3) {
                bowlCount = 1;
            }

            if (DataLoadService.shopRecUrlMap != null) {
                String tempUrl = DataLoadService.shopRecUrlMap.get(shopId);
                if (tempUrl != null) {
                    url = tempUrl;
                }
            }

            ResponseEntity<String> recImgResult = new RestTemplate().postForEntity(url, entity, String.class);

            try {
                String resultStr = recImgResult.getBody();

                System.out.println(resultStr);
                logger.info("local识别结果：{}", resultStr);
                if (resultStr == null) {
                    logger.info("本地模型识别无结果=");
                    return null;
                }
                resultStr = resultStr.substring(resultStr.indexOf("results")-2);
                ImgRecResult resResult = JsonUtil.parse(resultStr, ImgRecResult.class);


                System.out.println(resResult.getNumber());

                if (resResult.getNumber() > 0) {

                    RecResult huaRecResult = new RecResult();
                    huaRecResult.setDetectionBoxes(new ArrayList<>());
                    huaRecResult.setDetectionClasses(new ArrayList<>());
                    huaRecResult.setDetectionScores(new ArrayList<>());

                    for (Results res : resResult.getResults()) {
                        int x1 = res.getLocation().getLeft();
                        int y1 = res.getLocation().getTop();

                        int x2 = res.getLocation().getLeft() + res.getLocation().getWidth();
                        int y2 = res.getLocation().getTop() + res.getLocation().getHeight();


                        List<Double> location = new ArrayList<>();
                        location.add(Double.valueOf(y1));
                        location.add(Double.valueOf(x1));
                        location.add(Double.valueOf(y2));
                        location.add(Double.valueOf(x2));

                        huaRecResult.getDetectionBoxes().add(location);
                        huaRecResult.getDetectionScores().add(res.getScore());
                        huaRecResult.getDetectionClasses().add(res.getName());
                    }


                    long endTime = System.currentTimeMillis();
                    logger.info("本地模型识别结果=" + JsonUtil.toJson(huaRecResult));
                    logger.info("本地模型识别完成=" + endTime + ",huawei rec intelval=" + (endTime - localrecStart));


                    return huaRecResult;
                }else {
                    long endTime = System.currentTimeMillis();
                    logger.info("本地模型识别无结果");
                    logger.info("本地模型识别完成=" + endTime + ",huawei rec intelval=" + (endTime - localrecStart));
                    return null;
                }
            } catch (IOException e) {
                e.printStackTrace();
                logger.info("本地模型识别错误：{}", e.getMessage());
                return null;
            }
        });

        return localRecFuture;
    }


    private Future<RecResult> getProductYp(List<ProductYpRef> productYpRefList, Integer shopId, String sourceImgOnInternet) {
        if (productYpRefList != null && productYpRefList.size() > 0) {
            logger.info("包含云澎菜品库商品: shopId:" + shopId);

            String url = DataLoadService.shopLocalRecUrlmap.get(shopId);
            Map<String, ProductYp> productYpSearchCodeMap = DataLoadService.shopProductYpSearchCodeMap.get(shopId);
            logger.info("url====={}", url);
            Future<RecResult> localRecFuture = ThreadManager.executorService.submit((Callable) () ->
                    {
                        long localrecStart = System.currentTimeMillis();

                        Map<String, String> param = new HashMap<>();
                        param.put("shopId", shopId + "");
                        param.put("imgUrl", sourceImgOnInternet);
                        String jsonParam = JsonUtil.toJson(param);

                        HttpEntity entity = new HttpEntity<>(jsonParam, baiduRecUtil.DEFAULT_JSON_HEADER_UTF8);


                        ResponseEntity<String> recImgResult = new RestTemplate().postForEntity(url, entity, String.class);

                        try {
                            String resultStr = recImgResult.getBody();

                            System.out.println(resultStr);
                            logger.info("local识别结果：{}", resultStr);
                            if (resultStr == null) {
                                logger.info("本地模型识别无结果=");
                                return null;
                            }
                            resultStr = resultStr.substring(resultStr.indexOf("results")-2);
                            ImgRecResult resResult = JsonUtil.parse(resultStr, ImgRecResult.class);


                            System.out.println(resResult.getNumber());

                            if (resResult.getNumber() > 0) {

                                RecResult result = new RecResult();
                                result.setDetectionBoxes(new ArrayList<>());
                                result.setDetectionClasses(new ArrayList<>());
                                result.setDetectionScores(new ArrayList<>());

                                for (Results  res : resResult.getResults()) {
                                    int x1 = res.getLocation().getLeft();
                                    int y1 = res.getLocation().getTop();

                                    int x2 = res.getLocation().getLeft() + res.getLocation().getWidth();
                                    int y2 = res.getLocation().getTop() + res.getLocation().getHeight();


                                    if (res.getScore() < 0.7) {
                                        continue;
                                    }
                                    ProductYp productYp = productYpSearchCodeMap.get(res.getName());

                                    if (productYp != null) {
                                        long area = res.getLocation().getWidth() * res.getLocation().getHeight();
                                        if (productYp.getMinArea() != null) {
                                            if (area < productYp.getMinArea().intValue()) {
                                                logger.info("本地模型识别面积过小==" + JsonUtil.toJson(res));
                                                continue;
                                            }
                                        }
                                        if (productYp.getMaxArea() != null) {
                                            if (area > productYp.getMaxArea().intValue()) {
                                                logger.info("本地模型识别面积过大==" + JsonUtil.toJson(res));
                                                continue;
                                            }
                                        }
                                    }
                                    List<Double> location = new ArrayList<>();
                                    location.add(Double.valueOf(y1));
                                    location.add(Double.valueOf(x1));
                                    location.add(Double.valueOf(y2));
                                    location.add(Double.valueOf(x2));

                                    result.getDetectionBoxes().add(location);
                                    result.getDetectionScores().add(res.getScore());
                                    result.getDetectionClasses().add(res.getName());
                                }


                                long endTime = System.currentTimeMillis();
                                logger.info("本地模型识别结果=" + JsonUtil.toJson(result));
                                logger.info("本地模型识别完成=" + endTime + ",huawei rec intelval=" + (endTime - localrecStart));


                                return result;
                            }else {
                                long endTime = System.currentTimeMillis();
                                logger.info("本地模型识别无结果");
                                logger.info("本地模型识别完成=" + endTime + ",huawei rec intelval=" + (endTime - localrecStart));
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                            logger.info("本地模型识别错误：{}", e.getMessage());
                        }
                        return null;
                    }
            );
            return localRecFuture;

        }

        return null;
    }


    private Set<Result> getRemoveList(List<Result> searchResultList, List<HuaweiProduct> huaweiProductList, int width,
                                       List<ProductRecResultDetailVONewWithLocation> productRecResultDetailVONewWithLocationList){
        Set<Result> needRemovedProductList = null;
        for (Result temp : searchResultList) {
            int x1 = temp.getLocation().getLeft();
            int y1 = temp.getLocation().getTop();

            int x2 = temp.getLocation().getLeft() + temp.getLocation().getWidth();
            int y2 = temp.getLocation().getTop() + temp.getLocation().getHeight();

            //右上角坐标
            int y11 = y1;
            int x11 = x2;

            String brief = temp.getDishes().get(0).getBrief();

            Integer searchProductId = null;
            for (ProductRecResultDetailVONewWithLocation productRecResultDetailVONewWithLocation : productRecResultDetailVONewWithLocationList) {
                if (
                        productRecResultDetailVONewWithLocation.getX1().intValue() == x1 &&
                        productRecResultDetailVONewWithLocation.getX2().intValue() == x2 &&
                        productRecResultDetailVONewWithLocation.getY1().intValue() == y1 &&
                        productRecResultDetailVONewWithLocation.getY2().intValue() == y2
                        ) {
                    searchProductId = productRecResultDetailVONewWithLocation.getProductId();
                    temp.getDishes().get(0).setBrief(searchProductId.toString());
                    break;
                }
            }

            if (huaweiProductList != null && huaweiProductList.size() > 0) {
                for (HuaweiProduct huaweiProduct : huaweiProductList) {
                    int y3 = huaweiProduct.getLocation().get(0).intValue();
                    int x3 = huaweiProduct.getLocation().get(1).intValue();

                    int y4 = huaweiProduct.getLocation().get(2).intValue();
                    int x4 = huaweiProduct.getLocation().get(3).intValue();

                    //右上角坐标
                    int y22 = y3;
                    int x22 = x4;

                    if (x1 < x3 && y1 < y3
                            && x2 > x4 && y2 > y4
                            ) {

                        logger.info("检测有图片包含: top=" + temp.getLocation().getTop() + ",searchProductId=" + searchProductId);
                        if (needRemovedProductList == null) {
                            needRemovedProductList = new HashSet<>();
                        }
                        needRemovedProductList.add(temp);
                        continue;

                        /*Integer huaweiProductId = huaweiProduct.getProductId();

                        if (huaweiProductId.equals(searchProductId)) {
                            logger.info("检测有图片包含: top=" + temp.getLocation().getTop());
                            if (needRemovedProductIdList == null) {
                                needRemovedProductIdList = new HashSet<>();
                            }
                            needRemovedProductIdList.add(searchProductId);
                            continue;
                        }*/
                    }

                    if (       ((x1 < (x3 + width) && x1 > (x3 - width))
                            && (y1 < (y3 + width) && y1 > (y3 - width)))

                            ||

                            ((x2 < (x4 + width) && x2 > (x4 - width))
                                    && (y2 < (y4 + width) && y2 > (y4 - width)))

                            ||

                            ((x11 < (x22 + width) && x11 > (x22 - width))
                                    && (y11 < (y22 + width) && y11 > (y22 - width)))

                            ) {

                            logger.info("检测到云澎菜品库商品,id:" + huaweiProduct.getProductId() +
                                    ",name=" + huaweiProduct.getProductName() + ",baiduTop:" + x3 + ",searchProductId=" + searchProductId);


                            if (needRemovedProductList == null) {
                                needRemovedProductList = new HashSet<>();
                            }
                            needRemovedProductList.add(temp);

                    }

                }
            }
        }

        return needRemovedProductList;
    }

}
